package com.netty.esc.utils;

import org.apache.http.HttpResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MessageUtil {

    public static String sendMessage(String phone) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "b75cf90d57d74dde86ba03ab4a71cf66";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        String code = VerifyingCode();
        querys.put("param", "**code**:"+code+",**minute**:5");
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        //测试模板
//        String testTemplateId = "908e94ccf08b4476ba6c876d13f084ad";
        String testTemplateId = "0fbdd4b7ea5347618ee2514a75f49adb";
        querys.put("templateId", testTemplateId);
        Map<String, String> bodys = new HashMap<>();


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //TODO: 短信服务返回状态码需要做处理
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            //正常示例
//            {
//                "msg": "成功",
//                    "smsid": "16565614329364584123421",  //批次号。可通过该ID查询发送状态或者回复短信。API接口可联系客服获取。
//                    "code": "0",
//                    "balance": "1234"  //账户剩余次数
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return code;
    }

    //生成六位随机数
    public static String VerifyingCode()
    {
        Random random=new Random();
        StringBuilder code= new StringBuilder();
        for (int i=0;i<6;i++)
        {
            code.append(random.nextInt(10));
        }
        System.out.println(code);
        return code.toString();
    }

    public static void main(String[] args) {
        sendMessage("15313553023");
    }
}
